<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Traits\TraitResource;
use App\Models\Admin;
use App\Models\DealData;
use App\Models\Exchange;
use App\Models\Permissions;
use App\Models\SummaryData;
use App\Models\SystemConfig;
use App\Models\TransactionUser;
use App\Models\Varietie;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;

class IndexController extends Controller
{
    use TraitResource;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $today_start    = strtotime(date('Y-m-d', time()));
        // 默认查询昨天的
        $start_time = date('Y-m-d', $today_start - 86400 * 30);
        $end_time   = date('Y-m-d', $today_start);
        $timeRes = [
            'start_time' => $start_time,
            'end_time' => $end_time,
        ];
        View::share($timeRes);
        $this->middleware('auth:admin');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * Description:
     * User: Vijay
     * Date: 2019/5/24
     * Time: 22:42
     */
    public function index()
    {
        $user        = Auth::user();
        $permissions = $user->getAllPermissions();
        $menu        = Permissions::getMenuTree($permissions->toArray());
        $site_name     = SystemConfig::query()->where('key', 'site_name')->value('value');
        return view('admin.index.index', [
            'admin' => $user,
            'menus' => $menu,
            'site_name' => $site_name
        ]);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * Description:
     * User: Vijay
     * Date: 2019/5/24
     * Time: 22:40
     */
    public function main()
    {
        $is_admin = $this->powerAdmin();
        if ($is_admin) {
            $transaction_users = TransactionUser::query()->pluck('admin_name as username', 'id');
        } else {
            $transaction_users = TransactionUser::query()->where('admin_id', Auth::id())->pluck('admin_name as username', 'id');
        }
        return view('admin.index.main', [
            'transaction_users' => $transaction_users,
            'is_admin' => $is_admin,
            'admin_id' => Auth::id()
        ]);
    }

    /**
     * 期分析
     */
    public function qi()
    {
        $is_admin = $this->powerAdmin();
        if ($is_admin) {
            $transaction_users = TransactionUser::query()->pluck('admin_name as username', 'id');
        } else {
            $transaction_users = TransactionUser::query()->where('admin_id', Auth::id())->pluck('admin_name as username', 'id');
        }
        return view('admin.index.qi', [
            'transaction_users' => $transaction_users,
            'is_admin' => $is_admin,
            'admin_id' => Auth::id()
        ]);
    }

    /**
     * Description:走势图
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/09/16
     * Time: 15:15
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function closing_price()
    {
        $is_admin = $this->powerAdmin();
        if ($is_admin) {
            $transaction_users = TransactionUser::query()->pluck('admin_name as username', 'id');
        } else {
            $transaction_users = TransactionUser::query()->where('admin_id', Auth::id())->pluck('admin_name as username', 'id');
        }
        $res =  $this->closingPrice();
        $parms = [
            'transaction_users' => $transaction_users,
            'is_admin' => $is_admin,
            'admin_id' => Auth::id()
        ];
        $res = array_merge($res, $parms);
        return view('admin.index.closing_price', $res);
    }

    /**
     * Description:买卖平开细分
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/26
     * Time: 11:47
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function sale_buy()
    {
        $is_admin = $this->powerAdmin();
        if ($is_admin) {
            $transaction_users = TransactionUser::query()->pluck('admin_name as username', 'id');
        } else {
            $transaction_users = TransactionUser::query()->where('admin_id', Auth::id())->pluck('admin_name as username', 'id');
        }
        $res =  $this->closingPrice();
        $varietie_combination = [];
        foreach ($res['varietie_codes'] as $val) {
            $varietie_combination[$val . '-卖-平'] = $val . '多（卖平）';
            $varietie_combination[$val . '-买-平'] = $val . '空（买平）';
        }
        $parms = [
            'transaction_users' => $transaction_users,
            'is_admin' => $is_admin,
            'admin_id' => Auth::id(),
            'varietie_combination' => $varietie_combination,
        ];
        $res = array_merge($res, $parms);
        return view('admin.index.sale_buy', $res);
    }

    /**
     * 获取分组
     */
    public function saleBuyVarietie(Request $request)
    {
        $exchange_id = $request->input('exchange_id', '');
        if (!$exchange_id) {
            return $this->resJson(0, '获取成功', []);
        }
        $codeList = Varietie::getVarietieList($exchange_id);
        $varietie_combination = [];
        if (empty($codeList)) {
            return $this->resJson(0, '获取成功', []);
        }
        foreach ($codeList as $val) {
            $varietie_combination[$val . '-卖-平'] = $val . '多（卖平）';
            $varietie_combination[$val . '-买-平'] = $val . '空（买平）';
        }
        return $this->resJson(0, '获取成功', $varietie_combination);
    }

    /**
     * Description:期分期
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/09/15
     * Time: 16:39
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function mainAjax(Request $request)
    {
        $times = $request->input('times', '');
        $admin_id = $request->input('admin_id', Auth::id());
        $is_admin = $this->powerAdmin();
        if (!$is_admin) {
            $admin_id = Auth::id();
        }
        $today = time();
        $today_start = strtotime(date('Y-m-d', $today));
        if ($times != '') {
            $timeArr = explode('~', $times);
            $start_time = trim($timeArr[0]);
            $end_time = trim($timeArr[1]);
        } else {
            // 默认查询昨天的
            $start_time = date('Y-m-d', $today_start - 86400);
            $end_time = date('Y-m-d', $today_start);
        }
        $timeRes = getTimeFormat('', $start_time, $end_time);
        //
        $res = [
            'deal_num' => 0, //交易手数
            'net_worth' => 0, //当前净值
            'max_net_worth' => 0, //最高净值
            'min_net_worth' => 0, //最低净值
            'max_retracement' => 0, //最大回撤
            'start_funds' => 0, //初始资金
            'end_funds' => 0, //末期资金
            'go_out_funds' => 0, //累计出入金
            'overlay_income' => 0, //累计收益
        ];
        $list = SummaryData::query()
            ->where('admin_id', $admin_id)
            ->whereBetween('deal_time_stamp', [$timeRes['start_time_str'], $timeRes['end_time_str']])
            ->orderBy('deal_time_stamp', 'ASC')
            ->get();
        $fene                     = []; //份额
        $worth                    = []; // 净值
        $risk                     = []; //风险度
        $timeline                 = []; //时间轴
        $customer_rights          = []; //客户权益
        $total_access_for_the_day = []; //存取合计
        foreach ($list as $key => $val) {
            $customer_rights[$key]          = $val->customer_rights;
            $total_access_for_the_day[$key] = $val->total_access_for_the_day;
            $risk[$key]                     = round((float)$val->risk / 100, 2);
            $timeline[$key]                 = date('Y-m-d', $val->deal_time_stamp);
            if ($key == 0) {
                $fene[$key]  = $val->customer_rights;
                $worth[$key] = round($val->customer_rights / $fene[$key], 2);
                // 初始资金
                $res['start_funds'] = $val->customer_rights;
            } else {
                if ($worth[$key - 1] == 0) {
                    $fene[$key] = $fene[$key - 1];
                } else {
                    $fene[$key] = round($fene[$key - 1] + $val->total_access_for_the_day / $worth[$key - 1], 2);
                }

                if ($fene[$key] == 0) {
                    $worth[$key] = $val->customer_rights;
                } else {
                    $worth[$key] = round($val->customer_rights / $fene[$key], 2);
                }
            }
            $res['end_funds'] = $val->customer_rights;
            // 当前净值
            $res['net_worth'] = $fene[$key];
            if ($res['max_net_worth'] < $worth[$key]) {
                $res['max_net_worth'] = $worth[$key];
            }
            if ($res['min_net_worth'] > $worth[$key]) {
                $res['min_net_worth'] = $worth[$key];
            }
            // 交易手数
            $res['deal_num'] += $val->deal_num;
            // 累计收益
            $res['overlay_income'] = round($res['overlay_income'] + $val->deal_profit_loss - $val->deal_fee, 2);
            // 出入金
            $res['go_out_funds'] = round($res['go_out_funds'] + $val->out_money_cny + $val->enter_money_cny, 2);
        }
        return $this->resJson(0, '获取成功', $res, [
            'worth'                    => $worth,
            'risk'                     => $risk,
            'timeline'                 => $timeline,
            'customer_rights'          => $customer_rights,
            'total_access_for_the_day' => $total_access_for_the_day,
        ]);
    }

    /**
     * Description:走势图数据
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/20
     * Time: 20:15
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function closingPriceAjax(Request $request)
    {
        $times          = $request->input('times', '');
        $exchange_id = $request->input('exchange_id', '');
        $varietie_codes = $request->input('varietie_codes', []);
        $varietie_code = $request->input('varietie_code', '');
        $admin_id = $request->input('admin_id', Auth::id());
        $transaction_users_id = $request->input('transaction_users_id', '');
        $is_admin = $this->powerAdmin();
        if (!$is_admin) {
            $admin_id = Auth::id();
        }
        if ($transaction_users_id != '') {
            $admin_id = TransactionUser::query()->where('id', $transaction_users_id)->value('admin_id');
        }

        $query       = DealData::query();
        $today       = time();
        $today_start = strtotime(date('Y-m-d', $today));
        if ($times != '') {
            $timeArr    = explode('~', $times);
            $start_time = trim($timeArr[0]);
            $end_time   = trim($timeArr[1]);
        } else {
            // 默认查询昨天的
            $start_time = date('Y-m-d', $today_start - 86400);
            $end_time   = date('Y-m-d', $today_start);
        }
        $timeRes = getTimeFormat('', $start_time, $end_time);
        $query->where('deal_time_stamp', '>=', $timeRes['start_time_str'])->where('deal_time_stamp', '<=', $timeRes['end_time_str']);

        if ($varietie_code != '') {
            $query->where('exchange_code', $varietie_code);
        } else if (!empty($varietie_codes)) {
            $query->whereIn('exchange_code', $varietie_codes);
        } elseif ($exchange_id != '') {
            $varietiesCode = Varietie::query()
                ->where('exchange_id', $exchange_id)
                ->pluck('code');
            $query->whereIn('exchange_code', $varietiesCode);
        }
        $query->where('admin_id', $admin_id)
            ->orderBy('deal_time_stamp', 'ASC');
        $res  = $query->get();
        $gap = ($timeRes['end_time_str'] - $timeRes['start_time_str']) / 86400;
        $xAxis = [];
        $data = [];
        for ($i = 0; $i <= $gap; $i++) {
            $xtime = date('Y-m-d', $timeRes['start_time_str'] + 86400 * $i);
            $xAxis[] = $xtime;
            $data[$xtime] = [
                'total_profit_loss' => 0.00, //品种累计盈亏
                'buy_open_num'      => 0, //买开手数
                'sell_open_num'     => 0, //卖开手数
                'num'               => 0, //总共次数
                'profit_num'        => 0, //盈手数
                'loss_num'          => 0, //亏手数
                'profit_loss'       => 0.00, //累计盈亏
                'fee'               => 0.00, //手续费
                'win_rate'          => 0, //胜率
                'deal_fee_scale'    => 0, //盈亏比
                'max_deficit'       => 0.00, //最大亏损
                'max_profit'        => 0.00, //最大盈利
                'deficit_mun'       => 0, //亏损次数
                'profit_mun'        => 0, //盈利次数
                'sum_profit'        => 0.00, //合计盈利
                'sum_deficit'       => 0.00, //合计亏损
                'average_deficit'   => 0.00, //平均亏损
                'average_profit'    => 0.00, //平均盈利
                'bear_num'          => 0, //空头手数,买平手数
                'bear_profit_loss'  => 0.00, //空头盈亏
                'bull_num'          => 0, //多头手数，卖平手数
                'bull_profit_loss'  => 0.00, //多头盈亏
            ];
        }
        // 循环分组
        foreach ($res as $re) {
            $deal_time = date('Y-m-d', $re->deal_time_stamp);
            $profit_loss = abs($re->profit_loss);
            $data[$deal_time]['total_profit_loss'] += $re->profit_loss;
            $data[$deal_time]['profit_loss']       += $profit_loss;
            $data[$deal_time]['fee']               -= $re->fee;
            $data[$deal_time]['num']               += 1;
            if ($re->profit_loss < 0) {
                $data[$deal_time]['deficit_mun'] += 1;
                if ($re->profit_loss < $data[$deal_time]['max_deficit']) {
                    $data[$deal_time]['max_deficit'] = $profit_loss;
                }
                $data[$deal_time]['sum_deficit'] += $profit_loss;
                $data[$deal_time]['loss_num']    += $re->num;
            } elseif ($re->profit_loss > 0) {
                $data[$deal_time]['profit_mun'] += 1;
                if ($re->profit_loss > $data[$deal_time]['max_profit']) {
                    $data[$deal_time]['max_profit'] = $profit_loss;
                }
                $data[$deal_time]['sum_profit'] += $profit_loss;
                $data[$deal_time]['profit_num'] += $re->num;
            }
            // 卖平买平
            if ($re->buy_sell == '买' && $re->open_flat == '平') {
                $data[$deal_time]['bear_num']         += $re->num;
                $data[$deal_time]['bear_profit_loss'] += $re->profit_loss;
            } elseif ($re->buy_sell == '卖' && $re->open_flat == '平') {
                $data[$deal_time]['bull_num']         += $re->num;
                $data[$deal_time]['bull_profit_loss'] += $re->profit_loss;
            } elseif ($re->buy_sell == '买' && $re->open_flat == '开') {
                $data[$deal_time]['buy_open_num'] += $re->num;
            } elseif ($re->buy_sell == '卖' && $re->open_flat == '开') {
                $data[$deal_time]['sell_open_num'] += $re->num;
            }
        }
        foreach ($data as $tim => $val) {
            $data[$tim]['fee'] = round($val['fee'], 2);
            if ($val['profit_num'] + $val['loss_num'] == 0) {
                $data[$tim]['win_rate'] = '0%';
            } else {
                $data[$tim]['win_rate'] = round($val['profit_num'] / ($val['profit_num'] + $val['loss_num']) * 100, 2);
            }
            if ($val['sum_deficit'] == 0) {
                $data[$tim]['deal_fee_scale'] = 0;
            } else {
                $data[$tim]['deal_fee_scale'] = round($val['sum_profit'] / $val['sum_deficit'], 2);
            }
            if ($val['loss_num'] == 0) {
                $data[$tim]['average_deficit'] = 0;
            } else {
                $data[$tim]['average_deficit'] = round($val['sum_deficit'] / $val['loss_num'], 2);
            }
            if ($val['profit_num'] == 0) {
                $data[$tim]['average_profit'] = 0;
            } else {
                $data[$tim]['average_profit'] = round($val['sum_profit'] / $val['profit_num'], 2);
            }
        }
        // 拼接图标数据
        $legendArr      = ['累计盈亏', '手续费', '最大亏损', '最大盈利', '亏损次数', '盈利次数', '合计盈利', '合计亏损', '平均亏损', '平均盈利', '空头手数', '空头盈亏', '多头手数', '多头盈亏'];
        $yAxis          = [
            [
                'name' => '累计盈亏',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '手续费',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '最大亏损',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '最大盈利',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '亏损次数',
                'type' => 'line',
                'data' => []
            ],
            [
                'name' => '盈利次数',
                'type' => 'line',
                'data' => []
            ],
            [
                'name' => '合计盈利',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '合计亏损',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '平均亏损',
                'type' => 'bat',
                'data' => []
            ],
            [
                'name' => '平均盈利',
                'type' => 'bat',
                'data' => []
            ],

            [
                'name' => '空头手数',
                'type' => 'line',
                'data' => []
            ],
            [
                'name' => '空头盈亏',
                'type' => 'bar',
                'data' => []
            ],
            [
                'name' => '多头手数',
                'type' => 'line',
                'data' => []
            ],
            [
                'name' => '多头盈亏',
                'type' => 'bar',
                'data' => []
            ]
        ];
        $codeNum        = [];
        $win_rate       = [];
        $deal_fee_scale = [];
        // 散点图
        $scatterArr = [];
        foreach ($data as $k => $v) {
            $codeNum[]           = $v['num'];
            $deal_fee_scale[]    = $v['deal_fee_scale'];
            $win_rate[]          = $v['win_rate'];
            $yAxis[0]['data'][]  = $v['profit_loss'];
            $yAxis[1]['data'][]  = $v['fee'];
            $yAxis[2]['data'][]  = $v['max_deficit'];
            $yAxis[3]['data'][]  = $v['max_profit'];
            $yAxis[4]['data'][]  = $v['deficit_mun'];
            $yAxis[5]['data'][]  = $v['profit_mun'];
            $yAxis[6]['data'][]  = $v['sum_profit'];
            $yAxis[7]['data'][]  = $v['sum_deficit'];
            $yAxis[8]['data'][]  = $v['average_deficit'];
            $yAxis[9]['data'][]  = $v['average_profit'];
            $yAxis[10]['data'][] = $v['bear_num'];
            $yAxis[11]['data'][] = $v['bear_profit_loss'];
            $yAxis[12]['data'][] = $v['bull_num'];
            $yAxis[13]['data'][] = $v['bull_profit_loss'];
            $scatterArr['buy'][] = [$k, $v['buy_open_num'] + $v['bear_num'], $v['buy_open_num'], $v['bear_num']];
            $scatterArr['sell'][] = [$k, $v['sell_open_num'] + $v['bull_num'], $v['sell_open_num'], $v['bull_num']];
        }
        return $this->resJson(0, '获取成功', $yAxis, [
            'legendArr'      => $legendArr,
            'xAxis'          => $xAxis,
            'codeNum'        => $codeNum,
            'deal_fee_scale' => $deal_fee_scale,
            'win_rate'       => $win_rate,
            'scatter_arr' => $scatterArr
        ]);
    }

    /**
     * Description:买卖平开
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/9/26
     * Time: 14:18
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function saleBuyAjax(Request $request)
    {
        $times                = $request->input('times', '');
        $exchange_id = $request->input('exchange_id', '');
        $varietie_combination = $request->input('varietie_combination', []);
        $varietie_codes       = $request->input('varietie_codes', []);
        $varietie_code = $request->input('varietie_code', '');
        $admin_id = $request->input('admin_id', Auth::id());
        $is_admin = $this->powerAdmin();
        if (!$is_admin) {
            $admin_id = Auth::id();
        }
        $query                = DealData::query();
        $today                = time();
        $today_start          = strtotime(date('Y-m-d', $today));
        if ($times != '') {
            $timeArr    = explode('~', $times);
            $start_time = trim($timeArr[0]);
            $end_time   = trim($timeArr[1]);
        } else {
            // 默认查询昨天的
            $start_time = date('Y-m-d', $today_start - 86400);
            $end_time   = date('Y-m-d', $today_start);
        }
        if (!empty($varietie_combination)) {
            $query->where(function ($query) use ($varietie_combination) {
                foreach ($varietie_combination as $k => $v) {
                    $arr = explode('-', $v);
                    if ($k == 0) {
                        $query->where('exchange_code', '=', $arr[0])->where('buy_sell', '=', $arr[1])->where('open_flat', '=', $arr[2]);
                    } else {
                        $query->orWhere(function ($query) use ($arr) {
                            $query->where('exchange_code', '=', $arr[0])->where('buy_sell', '=', $arr[1])->where('open_flat', '=', $arr[2]);
                        });
                    }
                }
            });
        } elseif (!empty($varietie_codes)) {
            $query->whereIn('exchange_code', $varietie_codes);
        } elseif ($exchange_id != '') {
            $varietiesCode = Varietie::query()
                ->where('exchange_id', $exchange_id)
                ->pluck('code');
            $query->whereIn('exchange_code', $varietiesCode);
        }
        $timeRes = getTimeFormat('', $start_time, $end_time);
        $query->where('deal_time_stamp', '>=', $timeRes['start_time_str'])->where('deal_time_stamp', '<=', $timeRes['end_time_str']);
        $query->where('admin_id', $admin_id)
            ->orderBy('deal_time_stamp', 'ASC');
        $res  = $query->get();
        $data = [];
        $zArr = [];
        $xArr = [];
        foreach ($res as $k => $v) {
            if ($v->open_flat == '开') {
                continue;
            }
            if (!isset($zArr[$v->exchange_code])) {
                $zArr[$v->exchange_code]['profit_loss'] = 0.00;
                $zArr[$v->exchange_code]['fee']         = 0.00;
            }
            $zArr[$v->exchange_code]['profit_loss'] = round($zArr[$v->exchange_code]['profit_loss'] + $v->profit_loss, 2);
            $zArr[$v->exchange_code]['fee']         = round($zArr[$v->exchange_code]['fee'] - $v->fee, 2);

            $code_buy_open_key = $v->exchange_code . '-' . $v->buy_sell . '-' . $v->open_flat;
            if (!isset($xArr[$code_buy_open_key])) {
                $buy_sell = '空';
                if ($v->buy_sell == '卖') {
                    $buy_sell = '多';
                }
                $xArr[$code_buy_open_key] = $v->exchange_code . $buy_sell . '（' . $v->buy_sell . $v->open_flat . '）';
            }
            if (!isset($data[$code_buy_open_key])) {
                $data[$code_buy_open_key]['profit_loss'] = 0.00;
                $data[$code_buy_open_key]['fee']         = 0.00;
            }
            $data[$code_buy_open_key]['profit_loss'] = round($data[$code_buy_open_key]['profit_loss'] + $v->profit_loss, 2);
            $data[$code_buy_open_key]['fee']         = round($data[$code_buy_open_key]['fee'] - $v->fee, 2);
        }

        $result = [
            'title'       => [],
            'profit_loss' => [],
            'fee'         => [],
        ];
        $zRes   = [
            'title'       => [],
            'profit_loss' => [],
            'fee'         => [],
        ];
        foreach ($data as $key => $val) {
            $result['title'][]       = $xArr[$key];
            $result['profit_loss'][] = $val['profit_loss'];
            $result['fee'][]         = $val['fee'];
        }
        foreach ($zArr as $k => $v) {
            $zRes['title'][]       = $k;
            $zRes['profit_loss'][] = $v['profit_loss'];
            $zRes['fee'][]         = $v['fee'];
        }
        return $this->resJson(0, '获取成功', $result, [
            'z_res' => $zRes
        ]);
    }
}
